package com.lei.retrofitfactory_one.http.token;

import com.blankj.utilcode.util.SPUtils;
import com.lei.retrofitfactory_one.http.api.API;
import com.lei.retrofitfactory_one.http.factory.BaseRetrofitFactory;
import com.lei.retrofitfactory_one.http.url.BaseUrl;
import com.lei.retrofitfactory_one.http.url.ClassType;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ProjectName : YoHuo001Java
 * @Author : 雷金泷
 * @Time : 2020/12/27 19:12
 * @Description : 文件描述
 */
public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;
        if (SPUtils.getInstance().contains(BaseUrl.TOKEN_KEY)){
            response = chain.proceed(addToken(request,SPUtils.getInstance().getString(BaseUrl.TOKEN_KEY)));
        }else {
            response = chain.proceed(request);
        }
        if (response.code() == BaseUrl.TOKEN_NON){
            String newtoken = createNewToken();
            SPUtils.getInstance().put(BaseUrl.TOKEN_KEY,newtoken);
            response = chain.proceed(addToken(request,newtoken));
        }
        return response;
    }

    private String createNewToken() throws IOException {
        return Objects.requireNonNull(BaseRetrofitFactory
                .create(ClassType.NETWORK, API.class)
                .token("password","651471431661901a216a1391961031a710916e18716a12d1",""))
                .execute()
                .body()
                .access_token;
    }

    private Request addToken(Request request, String token) {
        return request
                .newBuilder()
                .addHeader("Authorization","bearer "+token)
                .build();
    }
}
